package com.jms.crawler.util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * csv文件操作工具类
 *
 */
public class CsvUtil {

    public static void writeCsv(String filePath, List<String> dataList, String headLabel) throws IOException {
        BufferedWriter writer = null;
        if (headLabel != null) {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath,false), StandardCharsets.UTF_8));
            writer.write(headLabel);
            writer.newLine();
        }
        if (dataList != null) {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath,true), StandardCharsets.UTF_8));
            writer.write(String.join(",", dataList));
            writer.newLine();
        }
        if (writer != null) writer.close();
    }

    public static List<String> readerCsv(InputStream inputStream) throws IOException {
        List<String> list = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        reader.readLine();
        String line;
        while ((line = reader.readLine()) != null) {
            String text = line.split(",") [2];
            list.add(text);
        }
        return list;
    }

}
